/**
 * @Title: BaseController.java
 * @Package com.qding.smart.common.web.controller
 * @Description: TODO
 * Copyright: Copyright (c) 2011 
 * Company:成都康赛电子科大信息技术有限责任公司
 * 
 * @author Comsys-Administrator
 * @date 2016年6月19日 下午4:15:59
 * @version V1.0
 */

package com.qding.park.common.web.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import com.qding.park.common.core.constant.CacheKeyThree;
import com.qding.park.common.core.exceptions.BaseException;
import com.qding.park.common.core.exceptions.ExceptionMessage;
import com.qding.park.common.core.exceptions.IExceptionHandle;
import com.qding.park.common.core.exceptions.auth.AuthException;
import com.qding.park.common.core.exceptions.business.validator.RchlValidatorException;
import com.qding.park.common.core.redis.JedisClient;
import com.qding.park.common.core.redis.SerializeUtils;
import com.qding.park.common.utils.ListUtil;
import com.qding.park.common.utils.string.StringUtil;
import com.qding.park.common.web.session.SessionInfo;
import com.qding.park.manager.pojo.PowerInfo;
import com.qding.park.manager.pojo.SOAServiceEnum;
import com.qding.smart.common.web.security.SysUserDTO;
import com.qding.smart.sso.client.entry.UserInfo;
import com.qding.smart.sso.client.util.SSOClientHelp;

/**
 * @ClassName: BaseController
 * @Description: TODO
 * @author Comsys-Administrator
 * @date 2016年6月19日 下午4:15:59
 *
 */

public abstract class BaseController implements ApplicationContextAware{
    
    
    
    protected ApplicationContext context;
	
    public static final String SESSION_KEY = "SMART_USER_SESSION";

	/**
	 * @Fields exportMaxNumber : 最大导出行数（用一句话描述这个变量表示什么）
	 */
	public static final Integer exportMaxNumber = 500000000;
	@Autowired
	public HttpServletRequest request;

	@Autowired
	public HttpServletResponse response;

	@Autowired
	public HttpSession session;
	
	@Autowired
	protected JedisClient  jedisClient;

	@Autowired
	public IExceptionHandle exceptionHandle;

	protected PowerInfo getPowerInfo() {

//		UserInfo user = SSOClientHelp.getUserInfo(request);
	    SysUserDTO sessionUser= (SysUserDTO) session.getAttribute(SESSION_KEY);
	    if(sessionUser==null){
	        throw new AuthException(AuthException.TypeEnum.EXCEPTION_AUTH.getId(), null,
                    ExceptionMessage.createExceptionMessage(AuthException.TypeEnum.EXCEPTION_SESSION.getDesc(),
                            "会话失效,请重新登录", "权限不足:"));
	    }
	    if(ListUtil.isEmpty(sessionUser.getParkList())){
	        throw new AuthException(AuthException.TypeEnum.EXCEPTION_AUTH.getId(), null,
                    ExceptionMessage.createExceptionMessage(AuthException.TypeEnum.EXCEPTION_SESSION.getDesc(),
                            "所管理车场为空", "权限不足:"));
	    }
		PowerInfo power = new PowerInfo();
		power.setAdminIs(sessionUser.isAdmin());
		power.setParkList(sessionUser.getParkList());
		return power;
	}

	
	
	protected void powerCheck(String parkId) throws AuthException {
		PowerInfo power = this.getPowerInfo();
		if (StringUtils.isBlank(parkId)) {
			if (ListUtil.isEmpty(power.getParkList()) && !power.isAdminIs()) {
				throw new AuthException(AuthException.TypeEnum.EXCEPTION_AUTH.getId(), null,
						ExceptionMessage.createExceptionMessage(AuthException.TypeEnum.EXCEPTION_AUTH.getDesc(),
								this.getUsername() + " 没有此车场的权限", "权限不足:"));
			}
		} else {
			if (!power.getParkList().contains(Integer.valueOf(parkId)) && !power.isAdminIs()) {
				throw new AuthException(AuthException.TypeEnum.EXCEPTION_AUTH.getId(), null,
						ExceptionMessage.createExceptionMessage(AuthException.TypeEnum.EXCEPTION_AUTH.getDesc(),
								this.getUsername() + " 没有此车场的权限", "权限不足:"));
			}
		}

	}

	protected String getUsername() {

		UserInfo user = SSOClientHelp.getUserInfo(request);

		return user.getUserName();
	}

	protected void analysisValid(BindingResult result) throws BaseException {

		if (result.hasErrors()) {

			List<ObjectError> errorList = result.getAllErrors();
			StringBuffer buffer = new StringBuffer();
			for (ObjectError error : errorList) {
				buffer.append("[");
				buffer.append(error.getDefaultMessage()).append("]");
				System.out.println(error.getDefaultMessage());
			}

			throw new RchlValidatorException(RchlValidatorException.TypeEnum.EXCEPTION_VALIDATOR.getId(), null,
					new ExceptionMessage(RchlValidatorException.TypeEnum.EXCEPTION_VALIDATOR.getDesc(),
							buffer.toString(), buffer.toString()));
		}

	}
	
	public void setApplicationContext(ApplicationContext arg0) throws BeansException {
	        this.context = arg0;
	 }
	
	protected <T> T getServiceObj(SOAServiceEnum serviceEnum,String supplyId,Class<T> t){
	   T resultObj= context.getBean(serviceEnum.getValue()+"_"+supplyId, t);
	    return resultObj;
	}
	
}
